from paho.mqtt import client as mqtt_client
import time
from ctypes import c_ubyte, cast, POINTER
from PIL import Image
import numpy as np




broker = 'b2b80af0.ala.cn-hangzhou.emqxsl.cn'
port = 8883
topic = 'date_time/server'
client_id = 'server'
# 如果 broker 需要鉴权，设置用户名密码
username = 'server'
password = 'aassdd'

b_image_path='img/draw_img_test2.bmp'
r_image_path='img/image.bmp'
# 定义两个unsigned char数组存放黑红图片数据
img_b = (c_ubyte * 15006)()
img_r = (c_ubyte * 15006)()
#初始化头

#二值图片转数组
def img_in_array(image_path,unsigned_char_array):
    #加载图片
    bitmap_image = Image.open(image_path)
    #数组->一维化->8个一组切片->列表化
    bit_8list=np.array(bitmap_image).flatten().reshape(-1, 8).tolist()
    for i in range(6):unsigned_char_array[i] = c_ubyte([0X00,0X01,0X90,0X01,0X2C,0X01][i])

    for i in range(len(bit_8list)):
        int_list = [int(bit) for bit in bit_8list[i]]
        # 将整数列表转换为二进制字符串
        binary_str = ''.join(str(bit) for bit in int_list)
        # 将二进制字符串转换为十六进制数，保留前缀'0x'
        hex_value_with_prefix = int(binary_str, 2)
        #print(hex_value_with_prefix)
        unsigned_char_array[i] = c_ubyte(hex_value_with_prefix)
    return unsigned_char_array


# 初始化图片数组
img_b = img_in_array(b_image_path,img_b)
img_r = img_in_array(b_image_path,img_r)
# 将数组转换为指针，并获取数据
img_b_data = cast(img_b, POINTER(c_ubyte))[0:15006]
img_r_data = cast(img_r, POINTER(c_ubyte))[0:15006]

# 合并两个二进制数据
combined_data = img_r_data+img_r_data
#变为bytearray格式

combined_data = bytearray(combined_data)

# MQTT连接函数
def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.tls_set(ca_certs='./emqxsl-ca.crt')
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

# MQTT发布函数
def publish(client):

    msg_count = 0
    msg="1122"
    time.sleep(1)
    result = client.publish(topic, combined_data)
    # result: [0, 1]
    status = result[0]
    if status == 0:
        print(f"Send  msg to topic `{topic}`")
    else:
        print(f"Failed to send message to topic {topic}")
    msg_count += 1


def run():
    client = connect_mqtt()
    client.loop_start()

    while 1:
        publish(client)
        for i in range(30):
            time.sleep(1)
            print(f"时间{20-i}")



if __name__ == '__main__':
    run()